package com.atguigu.spzx.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.constant.RedisKeyConstant;
import com.atguigu.spzx.common.entity.UserInfo;
import com.atguigu.spzx.common.result.Result;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import com.atguigu.spzx.common.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * AuthGlobalFilter
 * </p>
 *
 * @author flyduck
 * @since 2023/11/5
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //如果请求路径满足 /api/**/auth/**
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(antPathMatcher.match("/api/**/auth/**", path)){
            //登陆校验
            UserInfo userInfo = this.getUserInfo(request);
            if (userInfo == null) {
                return out(exchange.getResponse(), Result.fail(ResultCodeEnum.LOGIN_AUTH));
            }
        }

        //放行
        return chain.filter(exchange);
    }

    private static Mono<Void> out(ServerHttpResponse response, Result r) {
        byte[] bits = JSONObject.toJSONString(r).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    private UserInfo getUserInfo(ServerHttpRequest request) {
        //获取token
        List<String> tokenList = request.getHeaders().get("token");
        if (CollectionUtil.isEmpty(tokenList)) {
            return null;
        }
        String token = tokenList.get(0);
        if(StrUtil.isBlank(token)){
            return null;
        }
        String userInfoJson = redisTemplate.opsForValue().get(RedisKeyConstant.USER_LOGIN_TOKEN_PREFIX + token);
        if (StrUtil.isBlank(userInfoJson)) {
            return null;
        }
        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        return userInfo;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
